<!-- 账单记录管理 -->
<script setup lang="ts">
defineOptions({
  name: "BillRecord",
  inheritAttrs: false,
});

import {
  getBillRecordPage,
  getBillRecordForm,
  deleteBillRecords,
  addBillRecord,
  updateBillRecord,
} from "@/api/billRecord";
import { getBillTagOptions } from "@/api/billTag";
import { getBillEntityOptions } from "@/api/billEntity";

import {
  BillRecordForm,
  BillRecordQuery,
  BillRecordPageVO,
} from "@/api/billRecord/types";

const queryFormRef = ref(ElForm); // 查询表单
const billRecordFormRef = ref(ElForm); // 账单记录表单

const loading = ref(false); //  加载状态
const removeIds = ref([]); // 删除账单记录ID集合 用于批量删除
const queryParams = reactive<BillRecordQuery>({
  pageNum: 1,
  pageSize: 10,
});

const props = defineProps({
  readOnly: {
    type: Boolean,
    default: false,
  },
  defaultQueryParams: {
    type: Object as PropType<BillRecordQuery>,
  },
  autoScroll: {
    type: Boolean,
    default: true,
  },
});

const dateTimeRange = ref<any>([]);
const total = ref(0); // 数据总数
const pageData = ref<BillRecordPageVO[]>(); // 账单记录分页数据
const billTagList = ref<OptionType[]>(); // Tag下拉数据源
const billEntityList = ref<OptionType[]>(); // entity下拉数据源

watch(dateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startTime = newVal[0];
    queryParams.endTime = newVal[1];
  } else {
    queryParams.startTime = undefined;
    queryParams.endTime = undefined;
  }
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "billRecord-form",
  width: 800,
  title: "",
});

// 账单记录表单数据
const formData = reactive<BillRecordForm>({});

// 校验规则
const rules = reactive({
  name: [{ required: true, message: "账单记录名不能为空", trigger: "blur" }],
  num: [{ required: true, message: "金额不能为空", trigger: "blur" }],
  date: [{ required: true, message: "账单记录日期不能为空", trigger: "blur" }],
  fromEntityId: [{ required: true, message: "转出实体", trigger: "blur" }],
  toEntityId: [{ required: true, message: "转入实体", trigger: "blur" }],
  billTagIds: [
    { required: false, message: "账单记录Tag不能为空", trigger: "blur" },
  ],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getBillRecordPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function resetQuery() {
  dateTimeRange.value = [];
  queryFormRef.value.resetFields();
  queryParams.startTime = undefined;
  queryParams.endTime = undefined;
  queryParams.pageNum = 1;
  handleQuery();
}

function SearchByParam(params: BillRecordQuery) {
  queryParams.keywords = params.keywords;
  queryParams.fromEntityId = params.fromEntityId;
  queryParams.toEntityId = params.toEntityId;
  queryParams.fromOrToEntityId = params.fromOrToEntityId;
  queryParams.startTime = params.startTime;
  queryParams.endTime = params.endTime;
  queryParams.pageNum = params.pageNum;
  queryParams.pageSize = params.pageSize;
  if (params.startTime && params.endTime) {
    dateTimeRange.value = [params.startTime, params.endTime];
  } else {
    dateTimeRange.value = [];
  }
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 加载角色下拉数据源 */
async function loadTagOptions() {
  getBillTagOptions().then((response) => {
    billTagList.value = response.data;
  });
}

/** 加载部门下拉数据源 */
async function loadEntityOptions() {
  getBillEntityOptions().then((response) => {
    billEntityList.value = response.data;
  });
}

/**
 * 打开弹窗
 *
 * @param type 弹窗类型  账单记录表单：billRecord-form | 账单记录导入：billRecord-import
 * @param id 账单记录ID
 */
async function openDialog(type: string, id?: number) {
  dialog.visible = true;
  dialog.type = type;

  if (dialog.type === "billRecord-form") {
    // 账单记录表单弹窗
    await loadTagOptions();
    await loadEntityOptions();
    if (id) {
      dialog.title = "修改账单记录";
      getBillRecordForm(id).then(({ data }) => {
        Object.assign(formData, { ...data });
      });
    } else {
      dialog.title = "新增账单记录";
    }
  }
}

/**
 * 关闭弹窗
 *
 * @param type 弹窗类型  账单记录表单：billRecord-form | 账单记录导入：billRecord-import
 */
function closeDialog() {
  dialog.visible = false;
  if (dialog.type === "billRecord-form") {
    billRecordFormRef.value.resetFields();
    billRecordFormRef.value.clearValidate();

    formData.id = undefined;
  }
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  if (dialog.type === "billRecord-form") {
    billRecordFormRef.value.validate((valid: any) => {
      if (valid) {
        const billRecordId = formData.id;
        loading.value = true;
        if (billRecordId) {
          updateBillRecord(billRecordId, formData)
            .then(() => {
              ElMessage.success("修改账单记录成功");
              closeDialog();
              handleQuery();
            })
            .finally(() => (loading.value = false));
        } else {
          addBillRecord(formData)
            .then(() => {
              ElMessage.success("新增账单记录成功");
              closeDialog();
              handleQuery();
            })
            .finally(() => (loading.value = false));
        }
      }
    });
  }
}, 3000);

/** 删除账单记录 */
function handleDelete(id?: number) {
  const billRecordIds = [id || removeIds.value].join(",");
  if (!billRecordIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除账单记录?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deleteBillRecords(billRecordIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  loadEntityOptions();
  loadTagOptions();
  if (props.defaultQueryParams) {
    SearchByParam(props.defaultQueryParams);
  } else {
    handleQuery();
  }
});

defineExpose({ SearchByParam });
</script>

<template>
  <div class="app-container">
    <!-- 账单记录列表 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="账单记录名"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="转出实体" prop="fromEntityId">
          <el-tree-select
            v-model="queryParams.fromEntityId"
            placeholder="请选择转出实体"
            :data="billEntityList"
            filterable
            check-strictly
            clearable
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="转入实体" prop="toEntityId">
          <el-tree-select
            v-model="queryParams.toEntityId"
            placeholder="请选择转入实体"
            :data="billEntityList"
            filterable
            check-strictly
            clearable
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="转入或转出实体" prop="fromOrToEntityId">
          <el-tree-select
            v-model="queryParams.fromOrToEntityId"
            placeholder="转入或转出实体"
            :data="billEntityList"
            filterable
            check-strictly
            clearable
            :render-after-expand="false"
          />
        </el-form-item>

        <el-form-item label="记录日期">
          <el-date-picker
            class="!w-[240px]"
            v-model="dateTimeRange"
            type="daterange"
            unlink-panels
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="Tag" prop="billTagIds">
          <el-select
            v-model="queryParams.billTagIds"
            multiple
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in billTagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery">
            <i-ep-refresh />
            重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header v-if="!props.readOnly">
        <div class="flex justify-between">
          <div>
            <el-button
              v-hasPerm="['sys:billRecord:add']"
              type="success"
              @click="openDialog('billRecord-form')"
              ><i-ep-plus />新增</el-button
            >
            <el-button
              v-hasPerm="['sys:billRecord:delete']"
              type="danger"
              :disabled="removeIds.length === 0"
              @click="handleDelete()"
              ><i-ep-delete />删除</el-button
            >
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="pageData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          label="记录日期"
          align="center"
          prop="date"
          width="180"
        />
        <el-table-column label="金额" align="center" prop="num" width="180" />
        <el-table-column
          key="name"
          label="账单记录名"
          align="center"
          prop="name"
        />
        <el-table-column
          key="fromEntityName"
          label="转出实体"
          align="center"
          prop="fromEntityName"
        />
        <el-table-column
          key="toEntityName"
          label="转入实体"
          align="center"
          prop="toEntityName"
        />

        <el-table-column label="Tags" align="center" prop="tagNames">
          <template #default="scope">
            <!-- <el-row :gutter="10" type="flex" justify="center">
              <el-col :span="6"
              v-for="(item, index) in scope.row.tagNames == null
                ? []
                : scope.row.tagNames.split(',')"
              :key="index"
              >
                <el-tag>{{ item }}</el-tag>
              </el-col>
            </el-row> -->
            <el-tag
              v-for="(item, index) in scope.row.tagNames == null
                ? []
                : scope.row.tagNames.split(',')"
              :key="index"
              >{{ item }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          fixed="right"
          width="220"
          v-if="!props.readOnly"
        >
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:billRecord:edit']"
              type="primary"
              link
              size="small"
              @click="openDialog('billRecord-form', scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:billRecord:delete']"
              type="primary"
              link
              size="small"
              @click="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :autoScroll="autoScroll"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialog.width"
      append-to-body
      @close="closeDialog"
    >
      <!-- 账单记录新增/编辑表单 -->
      <el-form
        v-if="dialog.type === 'billRecord-form'"
        ref="billRecordFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="金额" prop="num">
          <!-- <el-input v-model="formData.num" placeholder="请输入金额" type="number"/> -->
          <el-input-number
            :controls="false"
            v-model="formData.num"
            :precision="2"
          />
        </el-form-item>
        <el-form-item label="账单记录名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入账单记录名" />
        </el-form-item>
        <el-form-item label="转出实体" prop="fromEntityId">
          <el-tree-select
            v-model="formData.fromEntityId"
            placeholder="请选择转出实体"
            :data="billEntityList"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="转入实体" prop="toEntityId">
          <el-tree-select
            v-model="formData.toEntityId"
            placeholder="请选择转入实体"
            :data="billEntityList"
            filterable
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="formData.date"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="Tag" prop="billTagIds">
          <el-select
            v-model="formData.billTagIds"
            multiple
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in billTagList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 弹窗底部操作按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
